Telegram Group & Telegram Channel
Скрытые фичи Enum: как выжать максимум

Многие используют Enum как простой список констант. Но у enum.Enum в Python есть куда больше возможностей — и они могут сделать код чище и мощнее.


Вот несколько приёмов, которые мало кто использует — но зря.


1. Добавление поведения в Enum


from enum import Enum

class Status(Enum):
DRAFT = 'draft'
PUBLISHED = 'published'
ARCHIVED = 'archived'

def is_visible(self):
return self in {Status.DRAFT, Status.PUBLISHED}


Теперь Status.DRAFT.is_visible() — это просто и элегантно.


2. Enum с полями


from enum import Enum

class Color(Enum):
RED = ('#FF0000', 'danger')
GREEN = ('#00FF00', 'safe')

def __init__(self, hex_code, label):
self.hex_code = hex_code
self.label = label



Color.RED.hex_code # '#FF0000'
Color.RED.label # 'danger'



3. Автоматические значения с auto()


from enum import Enum, auto

class Role(Enum):
ADMIN = auto()
USER = auto()
GUEST = auto()


Удобно, если не важны конкретные значения, а нужны уникальные.


4. Строгая сериализация

В реальных приложениях (API, базы) лучше контролировать сериализацию enum'ов:


import json

class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.value
return super().default(obj)

json.dumps(Status.PUBLISHED, cls=CustomEncoder) # "published"



5. Сравнение по значению


Status('draft') == Status.DRAFT # True
Status('draft') is Status.DRAFT # True (enum гарантирует singleton)


Итого: Enum — это не просто константы. Это лёгкий способ инкапсулировать поведение и данные, улучшить читаемость и сделать код устойчивее к ошибкам.

👉@BookPython



tg-me.com/BookPython/3623
Create:
Last Update:

Скрытые фичи Enum: как выжать максимум

Многие используют Enum как простой список констант. Но у enum.Enum в Python есть куда больше возможностей — и они могут сделать код чище и мощнее.


Вот несколько приёмов, которые мало кто использует — но зря.


1. Добавление поведения в Enum


from enum import Enum

class Status(Enum):
DRAFT = 'draft'
PUBLISHED = 'published'
ARCHIVED = 'archived'

def is_visible(self):
return self in {Status.DRAFT, Status.PUBLISHED}


Теперь Status.DRAFT.is_visible() — это просто и элегантно.


2. Enum с полями


from enum import Enum

class Color(Enum):
RED = ('#FF0000', 'danger')
GREEN = ('#00FF00', 'safe')

def __init__(self, hex_code, label):
self.hex_code = hex_code
self.label = label



Color.RED.hex_code # '#FF0000'
Color.RED.label # 'danger'



3. Автоматические значения с auto()


from enum import Enum, auto

class Role(Enum):
ADMIN = auto()
USER = auto()
GUEST = auto()


Удобно, если не важны конкретные значения, а нужны уникальные.


4. Строгая сериализация

В реальных приложениях (API, базы) лучше контролировать сериализацию enum'ов:


import json

class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.value
return super().default(obj)

json.dumps(Status.PUBLISHED, cls=CustomEncoder) # "published"



5. Сравнение по значению


Status('draft') == Status.DRAFT # True
Status('draft') is Status.DRAFT # True (enum гарантирует singleton)


Итого: Enum — это не просто константы. Это лёгкий способ инкапсулировать поведение и данные, улучшить читаемость и сделать код устойчивее к ошибкам.

👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3623

View MORE
Open in Telegram


Библиотека Python разработчика | Книги по питону Telegram | DID YOU KNOW?

Date: |

How to Use Bitcoin?

n the U.S. people generally use Bitcoin as an alternative investment, helping diversify a portfolio apart from stocks and bonds. You can also use Bitcoin to make purchases, but the number of vendors that accept the cryptocurrency is still limited. Big companies that accept Bitcoin include Overstock, AT&T and Twitch. You may also find that some small local retailers or certain websites take Bitcoin, but you’ll have to do some digging. That said, PayPal has announced that it will enable cryptocurrency as a funding source for purchases this year, financing purchases by automatically converting crypto holdings to fiat currency for users. “They have 346 million users and they’re connected to 26 million merchants,” says Spencer Montgomery, founder of Uinta Crypto Consulting. “It’s huge.”

Tata Power whose core business is to generate, transmit and distribute electricity has made no money to investors in the last one decade. That is a big blunder considering it is one of the largest power generation companies in the country. One of the reasons is the company's huge debt levels which stood at ₹43,559 crore at the end of March 2021 compared to the company’s market capitalisation of ₹44,447 crore.

Библиотека Python разработчика | Книги по питону from kr


Telegram Библиотека Python разработчика | Книги по питону
FROM USA